﻿using System.Collections.Generic;

using System.IO;
using Commons = NougakudoCompanion.Commons;

namespace AdminWeb.Models
{
    static public class Helper
    {
        /// <summary>
        /// Get role instances data from table storage.
        /// </summary>
        /// <param name="runtime"></param>
        /// <returns>Role instances data</returns>
        static internal List<string> GetInstanceIDs(Commons.Runtime runtime)
        {
            var instances = new List<string>();
            var ret = NougakudoCompanion.Commons.TableStorageHelper.GetInstnaces();
            if (!ret.Item1)
            {
                instances.Add(runtime.Environment.RoleInstanceID);
            }
            else
            {
                if (ret.Item3.Count == 0)   // Add for  Refine role instance data.
                {
                    NougakudoCompanion.Utils.InstancesManagement.Initialize();
                    var item = new Commons.CompanionInstance(runtime.Environment.RoleInstanceID);
                    item.MachineName = System.Environment.MachineName;
                    ret.Item3.Add( item );
                }
                foreach (var instance in ret.Item3)
                {
                    instances.Add(instance.RowKey);
                }
            }
            return instances;
        }

        /// <summary>
        /// Get array data of tab separator strings.
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        static public string[] GetColums(string row)
        {
            if (row == "") return null;
            return row.Split('\t');
        }

        /// <summary>
        /// Download a data from blob storage.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="logType">Log name</param>
        /// <param name="instance">Role instance id</param>
        /// <returns>File name of downloaded file.</returns>
        static internal string GetDataFromBlob(Commons.Runtime runtime, string logType, string instance)
        {
            var name = logType + "-" + instance;
            var file = Path.Combine(runtime.Environment.DownloadFolder, name);
            var ret = NougakudoCompanion.Commons.BlobStorageHelper.DownloadBlob(runtime.Environment, name, file);
            if (!ret.Item1)
                return "";

            return file;
        }

    }
}